/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.interceptor;

import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 参数、url、SQL 相关安全非法数据验证
 * 
 * @author Administrator
 * @version $Id: ParamInterceptor.java, v 0.1 2018年11月26日 下午5:19:15 Administrator Exp $
 */
public class XSSInterceptor implements HandlerInterceptor {
  private String param = ""; // 参数名称
  private String paramValue = ""; // 参数值
  private String str = "";
  private String[] characterParams = null;
  private boolean OK = true;

  /**
   * 参数
   * 
   * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse, java.lang.Object)
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    // 页面缓存清空设置
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    boolean status = false;
    Enumeration<?> params = request.getParameterNames();
    while (params.hasMoreElements()) {
      param = (String) params.nextElement();
      String[] values = request.getParameterValues(param);
      paramValue = "";
      if (OK) {// 过滤字符串为0个时 不对字符过滤
        for (int i = 0; i < values.length; i++) {
          paramValue = paramValue + values[i];// 比这样写好 paramValue = values[i];
        }
        // 转换成小写
        paramValue = paramValue.toLowerCase();
        // System.out.print("paramValue=" + paramValue);
        characterParams = new String[] {"mouseo", "click", "blur", "focus", "change", "eval",
            "expression", "alert(", "<script"};
        for (int i = 0; i < characterParams.length; i++) {
          if (paramValue.indexOf(characterParams[i]) != -1) {
            // System.out.println(paramValue + "1111111111");
            str = characterParams[i];
            status = true;
            break;
          }
          if (status)
            break;
        }
        String badStr = "";
        // if (param.equals("newstype")) {
        // badStr =
        // "'|and|exec|<|>|&|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|"
        // + "char|declare|sitename|net user|xp_cmdshell|like'|and|exec|execute|insert|create|drop|"
        // + "table|from|grant|use|group_concat|column_name|"
        // +
        // "information_schema.columns|table_schema|union|where|select|delete|update|count|*|chr|mid|master|truncate|char|declare|--|like|%|+|#";
        // } else {
        badStr =
            "'@|;|and|or|exec|<|>|&|execute|create|insert|select|delete|update|drop|*|%|chr|master|truncate|"
                + "char|declare|sysobjects|join|print|like'|table|from|grant|use|group_concat|exists|"
                + "information_schema.columns|table_schema|union|where|alter|count|*|--|like|#|sp_executesql";

        // }
        String[] badStrs = badStr.split("\\|");
        String[] specials = new String[] {"orderfield", "orderflag", "createtime", "creatorname"};
        boolean bool_specials = false; // 标识对特殊字符不拦截
        for (int i = 0; i < badStrs.length; i++) {
          if (paramValue.startsWith(badStrs[i])) {
            // if (paramValue.indexOf(badStrs[i]) != -1) {
            for (String str : specials) {
              if (paramValue.toLowerCase().indexOf(str.toLowerCase()) != -1) {
                bool_specials = true;
                break;
              }
            }
            if (bool_specials == false) {
              status = true;
              str = badStrs[i];
              break;
            } else {
              status = false;
            }
          }
          if (status)
            break;
        }
      }
    }

    // 包含这三个的额页面不过滤 登录相关
    boolean status_url = true;
    StringBuffer url = request.getRequestURL();
    String file[] = url.toString().split("/");
    if (file[file.length - 1].contains("login") || file[file.length - 1].contains("setcookie")
        || file[file.length - 1].contains("redirect") || file[file.length - 1].contains("client"))

    {
      status_url = false;
    }
    if (status && status_url)

    {
      // System.out.println("请求路径==" + request.getRequestURL());
      PrintWriter out = response.getWriter();
      String outstr = "<script language='javascript'>alert('对不起！您输入内容包含有非法字符:\\" + str
          + "');window.history.go(-1);</script>";
      out.print(outstr);
      return false;
    } else

    {
      return true;
    }

  }

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse, java.lang.Object,
   *      org.springframework.web.servlet.ModelAndView)
   */
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {

  }

  /**
   * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
   */
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {

  }

}
